package com.fangsiqi.mashibing;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

// 使用Java反射拿到Unsafe对象
public class UnsafeDemo {
	private int value;

	public static void main(String[] args) throws NoSuchFieldException {
		Unsafe unsafe=getUnsafe();
		// 拿到value属性在UnsafeDemo中的内存偏移量
		long offset=unsafe.objectFieldOffset(UnsafeDemo.class.getDeclaredField("value"));
		System.out.println(unsafe);
		System.out.println(offset);
		// 修改UnsafeDemo对象中的value属性，基于CAS实现自增
		UnsafeDemo	unsafeDemo=new UnsafeDemo();
		System.out.println(unsafeDemo);
		// 获取oldValue
		int oldValue=unsafeDemo.value;
		// 基于Unsafe做修改
		unsafe.compareAndSwapInt(unsafeDemo,offset,oldValue,1);
		// 基于CAS自增1后，查看unsafeDemo中的value属性
		System.out.println(unsafeDemo.value);
	}



	public static Unsafe getUnsafe() {
		Unsafe unsafe=null;
		try {
			Field field = Unsafe.class.getDeclaredField("theUnsafe");
			field.setAccessible(true);
			unsafe=(Unsafe)field.get(null);
		} catch (Exception e) {
			// throw new RuntimeException(e);
			e.printStackTrace();
		}
		return unsafe;
	}
}
